import { onMounted, onUnmounted, reactive, ref } from 'vue';
import Player, { IPlayerOptions } from 'xgplayer'
import HlsPlugin from 'xgplayer-hls'
import { FullVideoConfig } from '@/types/JSX';
import 'xgplayer/dist/index.min.css'

export default function(props, emit) {
  const Events = Player.Events
  const definitionList = ref([])
  const player = ref(null)
  // 默认配置
  const defaultVideoConfig: FullVideoConfig = {
    id: 'root',
    lang: 'zh',
    url: '',
    width: '100%',
    height: '100%',
    plugins: [],
    volume: 0.6,
    loop: false,
    poster: '',
    marginControls: false,
    download: false,
    fitVideoSize: 'fixed',
    videoFillMode: 'contain',
    seekedStatus: 'play'
  }
  onMounted(() => {
    // 视频配置
    const videoConfig: FullVideoConfig = reactive(Object.assign({}, defaultVideoConfig, props.config))
    // 如果是移动端，则直接赋值可视区域宽高设置
    if (methods.deviceCheck()) {
      videoConfig.width = methods.getViewportSize().width
      videoConfig.height = methods.getViewportSize().height
      window.addEventListener('orientationchange', methods.orientationChange);
    // 如果是pc端，则按照传入参数宽高设置视频插件及外层自定义dom
    } else {
      const linpengVideoPlayer = document.querySelector('#linpengVideoPlayer') as HTMLElement
      linpengVideoPlayer.style.width = (videoConfig.width as string).match(/px|%|[r]em/) ? videoConfig.width as string : videoConfig.width + 'px'
      linpengVideoPlayer.style.height = (videoConfig.height as string).match(/px|%|[r]em/) ? videoConfig.height as string : videoConfig.height + 'px'
    }
    // 当清晰度列表无值时，不初始化
    if (props.definitionList.length === 0) return;
    definitionList.value = props.definitionList.map(item => {
      return {
        definition: item.name, // 清晰度
        url: item.url,
        text: {
          zh: item.name // 显示中文文案
        }
      }
    })
    // 当视频格式为m3u8时，加载hls播放插件
    if (definitionList.value[0].url.includes('m3u8')) {
      videoConfig.plugins.push(HlsPlugin)
      if (props.config.defaultLevel) { // 有默认清晰度时就选默认的，没有则选第一个
        const originSelect = definitionList.value.find(item => item.definition === props.config.defaultLevel)
        videoConfig.definition = {
          defaultDefinition: originSelect ? originSelect.definition : definitionList.value[0].definition, // 可能视频集合中没有此清晰度
          list: definitionList.value
        }
      } else {
        videoConfig.definition = {
          defaultDefinition: definitionList.value[0].definition,
          list: definitionList.value
        }
      }
      if (videoConfig.hls === undefined) {
        videoConfig.hls = {
          preloadTime: 6000,
          bufferBehind: 3000
        }
      }
    }
    // 默认赋值列表首值为播放路径
    // videoConfig.url = definitionList.value[0]?.url
    if (props.config.defaultLevel) {
      const originSelect = definitionList.value.find(item => item.definition === props.config.defaultLevel)
      videoConfig.url = originSelect ? originSelect.url : definitionList.value[0]?.url // 可能视频集合中没有此清晰度
    } else {
      videoConfig.url = definitionList.value[0]?.url
    }
    // 实例化视频播放器
    player.value = new Player(videoConfig as IPlayerOptions)
    emit('get-player', player.value)
    methods.eventListener()
  })
  onUnmounted(() => {
    window.removeEventListener('orientationchange', methods.orientationChange);
  })
  const methods = {
    /**
     * 当前运行设备检测
     * @returns boolean 移动端 => true, pc端 => false
     */
    deviceCheck() {
      // ipad、iphone竖屏；Andriod横屏
      if (window.orientation === 90 || window.orientation === -90) {
        // 给后续横竖屏做拓展留位置
        return true
      // ipad、iphone横屏；Andriod竖屏
      } else if (window.orientation === 0 || window.orientation === 180) {
        // 给后续横竖屏做拓展留位置
        return true
      // pc端
      } else {
        return false
      }
    },
    /**
     * 全局事件监听
     */
    eventListener() {
      /** 视频内容开始加载 */
      player.value.on(Events.LOAD_START, () => {
        emit('event', {
          eventName: Events.LOAD_START
        })
      })
      /** 视频起播数据加载完成 */
      player.value.on(Events.LOADED_DATA, () => {
        emit('event', {
          eventName: Events.LOADED_DATA
        })
      })
      /** 播放 */
      player.value.on(Events.PLAY, () => {
        emit('event', {
          eventName: Events.PLAY
        })
      })
      /** 暂停 */
      player.value.on(Events.PAUSE, () => {
        emit('event', {
          eventName: Events.PAUSE
        })
      })
      /** 结束 */
      player.value.on(Events.ENDED, () => {
        emit('event', {
          eventName: Events.ENDED
        })
      })
      /** 错误 */
      player.value.on(Events.ERROR, (error) => {
        console.log(error)
        emit('event', {
          eventName: Events.ERROR,
          eventValue: error
        })
      })
      /** （暂停、卡顿后）恢复播放 */
      player.value.on(Events.PLAYING, () => {
        emit('event', {
          eventName: Events.PLAYING
        })
      })
      /** seek播放 */
      player.value.on(Events.SEEKING, () => {
        emit('event', {
          eventName: Events.SEEKING
        })
      })
      /** seek完成 */
      player.value.on(Events.SEEKED, () => {
        emit('event', {
          eventName: Events.SEEKED
        })
      })
      /** 播放时间改变 */
      player.value.on(Events.TIME_UPDATE, (_val) => {
        emit('event', {
          eventName: Events.TIME_UPDATE,
          eventValue: {
            currentTime: player.value.currentTime, // 视频当前的播放时间, 单位：s
            duration: player.value.duration, // 视频时长，单位：s
            cumulateTime: player.value.cumulateTime // 累计播放时长， 单位：s
          }
        })
      })
      /** 等待加载数据 */
      player.value.on(Events.WAITING, () => {
        emit('event', {
          eventName: Events.WAITING
        })
      })
      /** 视频缓冲足够数据，可以播放 */
      player.value.on(Events.CANPLAY, () => {
        emit('event', {
          eventName: Events.CANPLAY
        })
      })
      /** 视频可以流畅播放 */
      player.value.on(Events.CANPLAY_THROUGH, () => {
        emit('event', {
          eventName: Events.CANPLAY_THROUGH
        })
      })
      /** 视频时长发生变化 */
      player.value.on(Events.DURATION_CHANGE, () => {
        emit('event', {
          eventName: Events.DURATION_CHANGE
        })
      })
      /** 音量变化 */
      player.value.on(Events.VOLUME_CHANGE, () => {
        emit('event', {
          eventName: Events.VOLUME_CHANGE,
          eventValue: {
            muted: player.value.muted, // 是否静音， Boolean
            volume: player.value.volume // 音量 0-1
          }
        })
      })
      /** 倍速变化 */
      player.value.on(Events.RATE_CHANGE, () => {
        emit('event', {
          eventName: Events.RATE_CHANGE,
          eventValue: player.value.playbackRate
        })
      })
      /** 全屏状态变化 */
      player.value.on(Events.FULLSCREEN_CHANGE, (isFullscreen) => {
        // 当前设备是移动端 && 退出全屏 => 重新布局
        if (methods.deviceCheck() && !isFullscreen) {
          methods.resize()
        }
        emit('event', {
          eventName: Events.FULLSCREEN_CHANGE,
          eventValue: isFullscreen
        })
      })
      /** 快捷键操作 */
      player.value.on(Events.SHORTCUT, (data) => {
        emit('event', {
          eventName: Events.SHORTCUT,
          // data
          // action: String | Function, // 该快捷键触发的行为
          // disable:  Boolean, // 是否禁用
          // key: String, // 功能定义key
          // keyCode: Number // 快捷键键值
          eventValue: data
        })
      })
      /** 内置插件用户行为监控 */
      player.value.on(Events.USER_ACTION, (data) => {
        switch (data.action) {
          /** 切换清晰度 */
          case 'change_definition':
            emit('event', {
              eventName: data.action,
              eventValue: {
                name: data.to.definition,
                url: data.to.url
              }
            })
            break;
        }
      })
    },
    /**
     * 移动端特有api
     * h5浏览器横竖屏检测
     */
    orientationChange() {
      if (methods.deviceCheck()) {
        setTimeout(() => {
          methods.resize()
        }, 20)
      }
    },
    /**
     * 移动端特有api
     * 获取可视区域的宽高
     * @returns obj
     */
    getViewportSize() {
      return {
        width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
        height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
      };
    },
    /**
     * 移动端特有api
     * 视频播放器重新布局
     */
    resize() {
      player.value?.setAttribute('style', `width: ${methods.getViewportSize().width}px; height: ${methods.getViewportSize().height}px;`)
    }
  }
}
